<template>
  <div class="login-wrap">
    <el-form
      :model="loginForm"
      :rules="rules"
      :label-position="labelPosition"
      ref="myForm"
      label-width="80px"
      class="login-from"
    >
      <h1>用户登录</h1>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <!-- 在文本框前面加element-ui字体图标 -->
        <!-- <el-input prefix-icon="el-icon-search"   v-model="loginForm.username"></el-input> -->
        <!-- 在文本框前面加自定义字体图标 -->
        <el-input
          placeholder="请输入用户名"
          prefix-icon="iconfont icon-user"
          v-model="loginForm.username"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <!-- 在文本框前面加自定义字体图标 -->
        <el-input
          placeholder="请输入密码"
          prefix-icon="iconfont icon-showpassword"
          type="password"
          v-model="loginForm.password"
        ></el-input>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button @click="submitForm('myForm')" class="login-btn" type="primary">登录</el-button>
        <el-button @click="resetForm('myForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/api/login'
export default {
  data() {
    return {
      // 表单选项前的提示信息的位置
      labelPosition: 'top',
      // 表单选项
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 定义表单验证规则
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 3, max: 10, message: '密码长度在3-10位', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          return false
        }
        // 表单验证成功后发起网络请求，进行登录校验
        const { data, meta } = await login(this.loginForm)
        if (meta.status !== 200) {
          return this.$message.error('登录失败')
        }
        this.$message.success('登录成功')
        // 从里面获取登录成功的token，并保存起来,建议保存在本地缓存的 sessionStorage：窗口关闭就失效
        sessionStorage.setItem('token', data.token)
        // 登录成功后跳转到后台首页
        this.$router.push('/home')
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-wrap {
  background-color: #324152;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  //登录表单
  .login-from {
    background-color: #fff;
    width: 500px;
    padding: 30px;
    border-radius: 5px;
    h1 {
      font-size: 24px;
    }
    //提交按钮
    .login-btn {
      // width: 100%;
    }
  }
}
</style>
